package com.gange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gange.dao.VideoMapper;
import com.gange.entity.Category;
import com.gange.entity.User;
import com.gange.entity.Video;
import com.gange.feignclient.CategoryFeignClient;
import com.gange.feignclient.UserFeignClient;
import com.gange.service.IVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 视频 服务实现类
 * </p>
 *
 * @author gange
 * @since 2022-11-07
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements IVideoService {
    @Autowired
    private CategoryFeignClient categoryFeignClient;
    @Autowired
    private UserFeignClient userFeignClient;
    @Override
    public IPage<Video> findAllByKeywords(String id, String name, Integer categoryId, String username, Page page) {
        //1.根据up主的名称找到up主的id信息
        List<Integer> userIds=new ArrayList<>();
        if(!StringUtils.isEmpty(username)){
            List<User> users = userFeignClient.selectByName(username);
            if(!ObjectUtils.isEmpty(users)){
                for(User user:users){
                    userIds.add(user.getId());
                }
            }
        }
        //2.分页查询视频信息。
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        if(!ObjectUtils.isEmpty(id)){
            wrapper.eq("id",id);
        }
        if(!StringUtils.isEmpty(name)){
            wrapper.eq("title",name);
        }
        if(!ObjectUtils.isEmpty(categoryId)){
            wrapper.eq("category_id",categoryId);
        }
        if(!ObjectUtils.isEmpty(username)){
            wrapper.in("uid",userIds);
        }
        IPage<Video> iPage = baseMapper.selectPage(page, wrapper);
        //当前页的视频信息
        List<Video> records = iPage.getRecords();
        if(!ObjectUtils.isEmpty(records)){
            for(Video video:records){
                //3.给视频包装up主信息
                Category category = categoryFeignClient.selectById(video.getCategoryId());
                video.setCategory(category.getName());
                //4.给视频保证类别信息。
                User user = userFeignClient.selectById(video.getUid());
                video.setUploader(user);
            }
        }
        System.out.println(iPage.getTotal()+"-----------------");
        return iPage;
    }
}
